<?php

/**
 * @version		$Id: example.php 14401 2010-01-26 14:10:00Z louis $
 * @package		Joomla
 * @subpackage	JFramework
 * @copyright	Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');
require_once ('acaweb/libs/AuthenticationService.php');

/**
 * Example Authentication Plugin
 *
 * @package		Joomla
 * @subpackage	JFramework
 * @since 1.5
 */
class plgAuthenticationAcaweb extends JPlugin {

    private $knownRoles = array(
        0 => "ROLE_STUDENT",
        1 => "ROLE_PROFESSOR",
        2 => "ROLE_DIRECTIVE",
        3 => "ROLE_PRACTICES_COORDINATOR",
        4 => "ROLE_ENTERPRISE",
        5 => "ROLE_GRADUATE",
        11 => "ROLE_REGISTERED",
    );

    /**
     * Constructor
     *
     * For php4 compatability we must not use the __constructor as a constructor for plugins
     * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
     * This causes problems with cross-referencing necessary for the observer design pattern.
     *
     * @param	object	$subject	The object to observe
     * @param	array	$config		An array that holds the plugin configuration
     * @since	1.5
     */
    function plgAuthenticationAcaweb(& $subject, $config) {
        parent::__construct($subject, $config);
    }

    /**
     * Support for joomla 1.7 authentication.
     * 
     * @param type $credentials
     * @param type $options
     * @param JAuthenticationResponse $response
     * @return boolean 
     */
    function onUserAuthenticate($credentials, $options,
            JAuthenticationResponse &$response) {
        return $this->onAuthenticate($credentials, $options, $response);
    }

    /**
     * This method should handle any authentication and report back to the subject
     *
     * @access	public
     * @param	array	$credentials	Array holding the user credentials
     * @param	array	$options		Array of extra options
     * @param	object	$response		Authentication response object
     * @return	boolean
     * @since	1.5
     */
    function onAuthenticate($credentials, $options,
            JAuthenticationResponse &$response) {
        /*
         * Here you would do whatever you need for an authentication routine with the credentials
         *
         * In this example the mixed variable $return would be set to false
         * if the authentication routine fails or an integer userid of the authenticated
         * user if the routine passes
         */
        $success = false;

        $service = new MembershipService();

        try {
            $success = $service->Login($credentials['username'], $credentials['password']);
        } catch (Exception $exc) {
            $response->status = JAUTHENTICATE_STATUS_FAILURE;
            $response->error_message = "Ha ocurrido un error al intentar autenticar, vuelve a intentarlo mas tarde.";
            return false;
        }


        if ($success->getSuccess()) {

            $CurrentUser = $success->getUser();
            $response->status = JAUTHENTICATE_STATUS_SUCCESS;
            $response->error_message = '';

            $response->email = $CurrentUser->getEmail();
            $response->fullname = $CurrentUser->getName();
            $response->username = $CurrentUser->getUsername();

            $extraData = array(
                "token" => $CurrentUser->getToken(),
                "alterUserName" => $CurrentUser->getAlterUsername()
            );
            
            $roles = array();
            
            foreach ($CurrentUser->getRol() as $rol) {
                $roles[] = $this->knownRoles[$rol];
            }

            $rolesData = $this->getExtraRoles($CurrentUser->getUsername());

            foreach ($rolesData as $value) {
                $roles[] = $value["role"];
                $params = $value["data"] ? json_decode($value["data"], true) : array();
                $extraData = array_merge($extraData, $params);
            }

            $session = JFactory::getSession();
            $session->set("__ExtraData", $extraData);

            $session->set("roles", $roles);

            return true;
        } else if ($this->justRegisteredLogin($credentials['username'], $credentials['password'], $response)) {
            return true;
        } else {
            $response->status = JAUTHENTICATE_STATUS_FAILURE;
            $response->error_message = $success->getMessage();
            return false;
        }
    }

    private function justRegisteredLogin($userName, $password,
            JAuthenticationResponse &$response) {
        $result = false;

        $dbo = JFactory::getDBO();
        $query = "
            SELECT id_inscrito 
            FROM acaweb_inscritos 
            WHERE numero_documento_identidad = $userName AND
                password = '" . md5($password) . "'
            ORDER BY fecha_inscripcion DESC";
        $dbo->setQuery($query);

        $id = $dbo->loadResult();

        $response->status = JAUTHENTICATE_STATUS_SUCCESS;
        $response->error_message = '';
        $response->email = "john@doe.com";
        $response->username = "0$id";

        $session = JFactory::getSession();
        $session->set("roles", array($this->knownRoles[11]));
        $result = true;

        return $result;
    }

    private function getExtraRoles($id) {
        $dbo = JFactory::getDBO();
        $query = "
            SELECT * 
            FROM acaweb_roles 
            WHERE user_id = '$id'";
        $dbo->setQuery($query);
        $result = $dbo->loadAssocList();

        return $result;
    }

}
